<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
function httpurl($url){
	$aurl = strtolower($url);
	if(strpos($aurl, 'http://')===false&&strpos($aurl, 'https://')===false){
		return 'http://'.$url;
	}
	return $url;
}
function host_url($uri = '') {
	if (isset($_SERVER['HTTP_HOST'])){
		$host_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
		$host_url .= '://'. $_SERVER['HTTP_HOST'];
	}else{
		$host_url = 'http://localhost';
	}
	return $host_url.ltrim($uri,'');
}
function singleurl($url){
	$url = strtolower($url);
	return str_replace(array('http://', 'https://'), array('', ''), $url);
}
function sizecount($size) {
	if($size >= 1073741824) {
		$size = round($size / 1073741824 * 100) / 100 . ' GB';
	} elseif($size >= 1048576) {
		$size = round($size / 1048576 * 100) / 100 . ' MB';
	} elseif($size >= 1024) {
		$size = round($size / 1024 * 100) / 100 . ' KB';
	} else {
		$size = $size . ' Bytes';
	}
	return $size;
}
function trimarray($array){
	$r = array();
	foreach ($array as $ar){
		$tr = trim($ar);
		if($tr&&$tr!=''){
			$r[] = $tr;
		}
	}
	unset($array);
	return $r;
}
function sysSubStr($string,$length,$append = false){
	if(strlen($string) <= $length ){
		return $string;
	}else{
		$i = 0;
		while ($i < $length){
			$stringTMP = substr($string,$i,1);
			if ( ord($stringTMP) >=224 ){
				$stringTMP = substr($string,$i,3);
				$i = $i + 3;
			}elseif( ord($stringTMP) >=192 ){
				$stringTMP = substr($string,$i,2);
				$i = $i + 2;
			}else{
				$i = $i + 1;
			}
			$stringLast[] = $stringTMP;
		}
		$stringLast = implode('',$stringLast);
		if($append){
			$stringLast .= '…';
		}
		return $stringLast;
	}
}

function daddslashes($string, $force = 1) {
	if(is_array($string)) {
		$keys = array_keys($string);
		foreach($keys as $key) {
			$val = $string[$key];
			unset($string[$key]);
			$string[addslashes($key)] = daddslashes($val, $force);
		}
	} else {
		$string = addslashes($string);
	}
	return $string;
}

/*
 * count() always return a wrong value
* */
function array_length($arr){
	$num = 0;
	if($arr&&is_array($arr)&&!empty($arr)){
		foreach ($arr as $value) {
			if($value!=null&&$value!=''){
				$num++;
			}
		}
	}
	return $num;
}
function array_remove(&$arr, $offset){
	array_splice($arr, $offset, 1);
}
function array_key(&$arr, $item){
	foreach($arr as $key => $val) {
		if($val==$item){
			return $key;
		}
	}
	return -1;
}
function delete_html($str){
	$str = trim($str);
	$str = strip_tags($str,"");
	$str = str_replace("\t","",$str);
	$str = str_replace("\r\n","",$str);
	$str = str_replace("\r","",$str);
	$str = str_replace("\n","",$str);
	$str = str_replace(" "," ",$str);
	$str = str_replace("&nbsp;"," ",$str);
	return trim($str);
}

function dhtmlspecialchars($string, $flags = null) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = dhtmlspecialchars($val, $flags);
		}
	} else {
		if($flags === null) {
			$string = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string);
			if(strpos($string, '&amp;#') !== false) {
				$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1', $string);
			}
		} else {
			if(PHP_VERSION < '5.4.0') {
				$string = htmlspecialchars($string, $flags);
			} else {
				if(strtolower(CHARSET) == 'utf-8') {
					$charset = 'UTF-8';
				} else {
					$charset = 'ISO-8859-1';
				}
				$string = htmlspecialchars($string, $flags, $charset);
			}
		}
	}
	return $string;
}

function useravatar($uid,$type="middle"){
	return base_url().useravatarpath($uid,$type);
}
function useravatarpath($uid,$type="middle"){
	$dir = useravatardir($uid);
	if($name = substr($uid, -2)){
		$filename = $name.'_avatar';
	}else{
		$filename = $uid.'_avatar';
	}
	if($type){
		return $dir.$filename."_{$type}.jpg";
	}else{
		return $dir.$filename.".jpg";
	}
}
function userres($uid,$type="bg",$ext='css'){
	return base_url().userrespath($uid,$type,$ext);
}

function userrespath($uid,$type="bg",$ext='css'){
	$dir = useravatardir($uid);
	if($name = substr($uid, -2)){
		$filename = $name;
	}else{
		$filename = $uid;
	}
	return $dir.$filename."_{$type}.{$ext}";
}

function useravatardir($uid){
	$uid = abs(intval($uid));
	$uid = sprintf("%09d", $uid);
	$dir1 = substr($uid, 0, 3);
	$dir2 = substr($uid, 3, 2);
	$dir3 = substr($uid, 5, 2);
	$dir = 'data/avatars/'.$dir1.'/'.$dir2.'/'.$dir3.'/';
	return $dir;
}

function pzxencode($str){
	return str_replace(array('+',' ','/','='), array('S0U0M','E0P0T0Y','P0OL0E','P9DK8G'),base64_encode($str));
}
function pzxdecode($str){
	return base64_decode(str_replace(array('S0U0M','E0P0T0Y','P0OL0E','P9DK8G'),array('+',' ','/','='),$str));
}
function encodekeywords($keywords){
	$keyws = array();
	foreach ($keywords as $word){
		$keyws[] = pzxencode(trim($word));
	}
	
	return implode(' ', $keyws);
}
function encodekeywordsarray($keywords){
	$keyws = array();
	foreach ($keywords as $word){
		$w['name'] = trim($word);
		$w['code'] = pzxencode(trim($word));
		$keyws[] = $w;
	}
	return array_length($keyws)>0?$keyws:false;
}

function clouddomain(){
	$setting = load_api('setting')->getSetting('cloudattach');
	if($setting&&$setting['provider']){
		$apisetting = $setting[$setting['provider']];
	}
	return $apisetting['domain']?rtrim($apisetting['domain'],'/').'/':base_url();
}

function thumburl($path,$type='middle',$cloud=false,$absolute=false){
	$ext = fileext($path);
	if($cloud){
		$baseurl = clouddomain();
	}else{
		$baseurl = ($absolute)?BASEPATH:base_url();
	}
	$type = $type?'_'.$type:'';
	return $baseurl.str_replace('.'.$ext, $type.'.'.$ext, $path);
}

function thumbpath($path,$type='middle'){
	$ext = fileext($path);
	return str_replace('.'.$ext, '_'.$type.'.'.$ext, $path);
}

function topicbanner($topid,$suffix='jpg'){
	$banner_info = banner_path($topid,'topic',$suffix);
	return base_url().$banner_info['dir'].$banner_info['filename'];
}

function groupbanner($gid,$suffix='jpg'){
	$banner_info = banner_path($gid,'group',$suffix);
	return base_url().$banner_info['dir'].$banner_info['filename'];
}

function banner_path($topid,$type='topic',$suffix='jpg'){
	$topid = abs(intval($topid));
	$topid = sprintf("%09d", $topid);
	$dir1 = substr($topid, 0, 3);
	$dir2 = substr($topid, 3, 2);
	$dir3 = substr($topid, 5, 2);
	$info = array();
	$dir = 'data/'.$type.'/'.$dir1.'/'.$dir2.'/'.$dir3.'/';
	$filename = substr($topid, -2).'_banner';
	return array('dir'=>$dir,'filename'=>$filename.".{$suffix}");
}

function array_to_str($arr,$coma=','){
	$pro = array();
	foreach ($arr as $k=>$v) {
		if($k!=null&&$k!=''&&$v!=null&&$v!='')
			$pro[] = "{$k}:{$v}";
	}
	$text = implode(",", $pro);
	return $text;
}

function str_to_arr($str,$coma=','){
	$arr = array();
	$f_array = explode($coma, $str);
	foreach ($f_array as $f) {
		$s_array = explode(':', $f);
		$arr[$s_array[0]] = $s_array[1];
	}
	return $arr;
}

function str_to_arr_list($array_str){
	$arr = array();
	if($array_str){
		$f_array = explode('|', $array_str);
		if(is_array($f_array)){
			foreach ($f_array as $f) {
				array_push($arr, str_to_arr($f,','));
			}
		}else{
			array_push($arr, $this->str_to_arr(str_replace('|', '', $view_history),$coma=','));
		}
		return $arr;
	}else{
		return array();
	}
}

function arr_list_to_str($array_list){
	$str = array();
	foreach ($array_list as $v) {
		$str[] = array_to_str($v);
	}
	$text = implode("|", $str);
	return $text;
}

function is_empty($var){
	if((!$var||$var=='false'||$var==null||strlen(trim($var))==0))
		return true;
	return false;
}


function unicode2utf($str){
	$result = '';
	if($str < 0x80){
		$result .= $str;
	}elseif($str < 0x800){
		$result .= chr(0xC0 | $str>>6);
		$result .= chr(0x80 | $str & 0x3F);
	}elseif($str < 0x10000){
		$result .= chr(0xE0 | $str>>12);
		$result .= chr(0x80 | $str>>6 & 0x3F);
		$result .= chr(0x80 | $str & 0x3F);
	} elseif($str < 0x200000) {
		$result .= chr(0xF0 | $str>>18);
		$result .= chr(0x80 | $str>>12 & 0x3F);
		$result .= chr(0x80 | $str>>6 & 0x3F);
		$result .= chr(0x80 | $str & 0x3F);
	}
	return $result;
}

function entities2utf8($unicode_c){
	$replacedString = preg_replace("/\\\\u([0-9abcdef]{4})/", "&#x$1;", $unicode_c);
	$unicode_c = mb_convert_encoding($replacedString, 'UTF-8', 'HTML-ENTITIES');
	return $unicode_c;
}

function rand_pop($arr){
	if($length = array_length($arr)){
		$i=($length>1)?rand(0,$length-1):0;
		return $arr[$i];
	}
	return null;
}

function getExtFromContentType($content_type){
	$fileext = '';
	switch($content_type){
		case 'image/jpeg':
		case 'image/pjpeg':
			$fileext = 'jpg';
			break;
		case 'image/png':
		case 'image/x-png':
			$fileext ='png';
			break;
		case 'image/gif':
			$fileext ='gif';
			break;
		case 'image/bmp':
			$fileext ='bmp';
			break;
		case 'image/tiff':
			$fileext ='tiff';
			break;
		case 'text/css':
			$fileext ='css';
			break;
		case 'text/html':
			$fileext ='html';
			break;
		case 'text/plain':
			$fileext ='txt';
			break;
		case 'text/rtf':
			$fileext ='rtf';
			break;
		case 'text/xml':
			$fileext ='xml';
			break;
		case 'video/mpeg':
			$fileext ='mpeg';
			break;
		case 'video/quicktime':
			$fileext ='mov';
			break;
		case 'video/x-msvideo':
			$fileext ='avi';
			break;
		case 'application/msword':
			$fileext ='doc';
			break;
		case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
			$fileext ='docx';
			break;
		case 'application/excel':
		case 'application/vnd.ms-excel':
		case 'application/msexcel':
			$fileext ='xls';
			break;
		case 'application/x-zip':
		case 'application/zip':
		case 'application/x-zip-compressed':
			$fileext ='zip';
			break;
		case 'audio/mpeg':
		case 'audio/mpg':
		case 'audio/mpeg3':
		case 'audio/mp3':
			$fileext ='mp3';
			break;
		case 'audio/x-wav':
		case 'audio/wav':
		case 'audio/wave':
			$fileext ='wav';
			break;
		case 'application/powerpoint':
		case 'application/vnd.ms-powerpoint':
			$fileext ='ppt';
			break;
		case 'application/x-tar':
			$fileext ='tar';
			break;
		case 'application/x-gzip-compressed':
			$fileext ='tgz';
			break;
		default:
			$fileext =false;
	}
	
	return $fileext;
}

function pzurlencode($url=""){
	$url = rawurlencode($url);
	$a = array("%3A", "%2F", "%40", "%3F", "%3D", "%26");
	$b = array(":", "/", "@", "?", "=", "&");
	$url = str_replace($a, $b, $url);
	return $url;
}

function get_contents($url,$retries=3,$needheader=false,$mr=10){
	if(function_exists('curl_init')){
		$ch = curl_init();
		
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
		curl_setopt($ch, CURLOPT_TIMEOUT, 20);
		curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ;
		curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
		curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1");
		curl_setopt($ch, CURLOPT_AUTOREFERER,true);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_FAILONERROR, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		if (is_empty(ini_get('open_basedir')) && (is_empty(ini_get('safe_mode'))||strtolower(ini_get('safe_mode'))=='off')) {
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
			//curl_setopt($ch, CURLOPT_MAXREDIRS, 100);
		} else {
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
			if ($mr > 0) {
				$newurl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
		
				$rch = curl_copy_handle($ch);
				curl_setopt($rch, CURLOPT_HEADER, true);
				curl_setopt($rch, CURLOPT_NOBODY, true);
				curl_setopt($rch, CURLOPT_FORBID_REUSE, false);
				curl_setopt($rch, CURLOPT_RETURNTRANSFER, true);
				do {
					curl_setopt($rch, CURLOPT_URL, $newurl);
					$header = curl_exec($rch);
					if (curl_errno($rch)) {
						$code = 0;
					} else {
						$code = curl_getinfo($rch, CURLINFO_HTTP_CODE);
						if ($code == 301 || $code == 302) {
							preg_match('/Location:(.*?)\n/', $header, $matches);
							$newurl = trim(array_pop($matches));
						} else {
							$code = 0;
						}
					}
				} while ($code && --$mr);
				curl_close($rch);
				if (!$mr) {
					if ($maxredirect === null) {
						trigger_error('Too many redirects. When following redirects, libcurl hit the maximum amount.', E_USER_WARNING);
					} else {
						$maxredirect = 0;
					}
					//return false;
				}
				curl_setopt($ch, CURLOPT_URL, $newurl);
			}
		}

		//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		
		$content = false;
		while (($content === false) && (--$retries > 0))
		{
			if($needheader){
				$content['data'] = curl_exec($ch);
				$content['content_type'] = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
				$content['content_length'] = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
			}else{
				$content = curl_exec($ch);
			}
		}
		curl_close($ch);
	}else{
		set_time_limit(0);
		$content = false;
		while (($content === false) && (--$retries > 0))
		{
			$content['data'] = @file_get_contents($url);
		}

	}
	if($content&&isset($content['data'])){
		if($dehtml = pgzdecode($content['data']))
			$content['data'] = $dehtml;
	}
	return $content;
}

function send_an_email($subject,$to_email,$message){

	$mail['subject'] = $subject;
	$mail['message'] = $message;
	$mail['from'] = $GLOBALS['G_SP']['email']['from'];
	$mail['sender'] = $GLOBALS['G_SP']['email']['sender'];

	$email_sender = spClass("Email");

	$email_sender->from($mail['from'], $mail['sender']);
	$email_sender->to($to_email);
	$email_sender->subject($mail['subject']);
	$email_sender->message($mail['message']);

	return $email_sender->send();
}

function safeEncoding($string,$outEncoding ='UTF-8'){
	$encoding = "UTF-8";
	for($i=0;$i<strlen($string);$i++){
		if(ord($string{$i})<128)
			continue;
		if((ord($string{$i})&224)==224) {
			$char = $string{++$i};
			if((ord($char)&128)==128){
				$char = $string{++$i};
				if((ord($char)&128)==128){
					$encoding = "UTF-8";
					break;
				}
			}
		}
		if((ord($string{$i})&192)==192){
			$char = $string{++$i};
			if((ord($char)&128)==128){
				$encoding = "GB2312";
				break;
			}
		}
	}

	if(strtoupper($encoding) == strtoupper($outEncoding))
		return $string;
	else
		return iconv($encoding,$outEncoding,$string);
}

function filename_check($filename){
	//preg_match("/^([a-zA-Z0-9_]+)\.(jpg|jpeg|gif|png|JPG|JPEG|GIF|PNG)$/", $filename, $matches);
	$ext = fileext($filename);
	return in_array($ext, array('jpg','jpeg','gif','png'));
}

function pfsget($path='/', $host='', $user_agent=''){
	if(!$path || !$host) return false;
	$user_agent = $user_agent ? $user_agent : "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1";

	$out = <<<HEADER
GET $path HTTP/1.1
Host: $host
User-Agent: $user_agent
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-cn,zh;q=0.5
Accept-Charset: GB2312,utf-8;q=0.7,*;q=0.7\r\n\r\n
HEADER;
	$fp = @fsockopen($host, 80, $errno, $errstr, 10);
	if (!$fp)  return false;
	if(!fputs($fp, $out)) return false;
	while ( !feof($fp) ) {
		$html .= fgets($fp, 1024);
	}
	fclose($fp);
	if($dehtml = pgzdecode($html))
		return $dehtml;
	else
		return $html;
}


function pgzdecode($data) {
	$len = strlen ( $data );
	if ($len < 18 || strcmp ( substr ( $data, 0, 2 ), "\x1f\x8b" )) {
		return null; // Not GZIP format (See RFC 1952)
	}
	$method = ord ( substr ( $data, 2, 1 ) ); // Compression method
	$flags = ord ( substr ( $data, 3, 1 ) ); // Flags
	if ($flags & 31 != $flags) {
		// Reserved bits are set -- NOT ALLOWED by RFC 1952
		return null;
	}
	// NOTE: $mtime may be negative (PHP integer limitations)
	$mtime = unpack ( "V", substr ( $data, 4, 4 ) );
	$mtime = $mtime [1];
	$xfl = substr ( $data, 8, 1 );
	$os = substr ( $data, 8, 1 );
	$headerlen = 10;
	$extralen = 0;
	$extra = "";
	if ($flags & 4) {
		// 2-byte length prefixed EXTRA data in header
		if ($len - $headerlen - 2 < 8) {
			return false; // Invalid format
		}
		$extralen = unpack ( "v", substr ( $data, 8, 2 ) );
		$extralen = $extralen [1];
		if ($len - $headerlen - 2 - $extralen < 8) {
			return false; // Invalid format
		}
		$extra = substr ( $data, 10, $extralen );
		$headerlen += 2 + $extralen;
	}

	$filenamelen = 0;
	$filename = "";
	if ($flags & 8) {
		// C-style string file NAME data in header
		if ($len - $headerlen - 1 < 8) {
			return false; // Invalid format
		}
		$filenamelen = strpos ( substr ( $data, 8 + $extralen ), chr ( 0 ) );
		if ($filenamelen === false || $len - $headerlen - $filenamelen - 1 < 8) {
			return false; // Invalid format
		}
		$filename = substr ( $data, $headerlen, $filenamelen );
		$headerlen += $filenamelen + 1;
	}

	$commentlen = 0;
	$comment = "";
	if ($flags & 16) {
		// C-style string COMMENT data in header
		if ($len - $headerlen - 1 < 8) {
			return false; // Invalid format
		}
		$commentlen = strpos ( substr ( $data, 8 + $extralen + $filenamelen ), chr ( 0 ) );
		if ($commentlen === false || $len - $headerlen - $commentlen - 1 < 8) {
			return false; // Invalid header format
		}
		$comment = substr ( $data, $headerlen, $commentlen );
		$headerlen += $commentlen + 1;
	}

	$headercrc = "";
	if ($flags & 1) {
		// 2-bytes (lowest order) of CRC32 on header present
		if ($len - $headerlen - 2 < 8) {
			return false; // Invalid format
		}
		$calccrc = crc32 ( substr ( $data, 0, $headerlen ) ) & 0xffff;
		$headercrc = unpack ( "v", substr ( $data, $headerlen, 2 ) );
		$headercrc = $headercrc [1];
		if ($headercrc != $calccrc) {
			return false; // Bad header CRC
		}
		$headerlen += 2;
	}

	// GZIP FOOTER - These be negative due to PHP's limitations
	$datacrc = unpack ( "V", substr ( $data, - 8, 4 ) );
	$datacrc = $datacrc [1];
	$isize = unpack ( "V", substr ( $data, - 4 ) );
	$isize = $isize [1];

	// Perform the decompression:
	$bodylen = $len - $headerlen - 8;
	if ($bodylen < 1) {
		// This should never happen - IMPLEMENTATION BUG!
		return null;
	}
	$body = substr ( $data, $headerlen, $bodylen );
	$data = "";
	if ($bodylen > 0) {
		switch ($method) {
			case 8 :
				// Currently the only supported compression method:
				$data = gzinflate ( $body );
				break;
			default :
				// Unknown compression method
				return false;
		}
	} else {
		//...
	}

	if ($isize != strlen ( $data ) || crc32 ( $data ) != $datacrc) {
		// Bad format!  Length or CRC doesn't match!
		return false;
	}
	return $data;
}
function sysSortArray($ArrayData,$KeyName1,$SortOrder1 = "SORT_ASC",$SortType1 = "SORT_REGULAR"){
	if(!is_array($ArrayData)){
		return $ArrayData;
	}

	// Get args number.
	$ArgCount = func_num_args();
	// Get keys to sort by and put them to SortRule array.
	for($I = 1;$I < $ArgCount;$I++){
		$Arg = func_get_arg($I);
		if($Arg!='SORT'){
			$KeyNameList[] = $Arg;
			$SortRule[]    = '$'.$Arg;
		}else{
			$SortRule[]    = $Arg;
		}
	}

	// Get the values according to the keys and put them to array.
	foreach($ArrayData AS $Key => $Info){
		foreach($KeyNameList AS $KeyName){
			${$KeyName}[$Key] = $Info[$KeyName];
		}
	}

	// Create the eval string and eval it.
	$EvalString = 'array_multisort('.join(",",$SortRule).',$ArrayData);';
	eval ($EvalString);
	return $ArrayData;
}

if (!function_exists('ucache')){
	function ucache($method, $name, $uid, $value = NULL){
		$avatar_dir = BASEPATH.useravatardir($uid);
		(!is_dir($avatar_dir))&&@mkdir($avatar_dir,0777,true);
		$sfile = $avatar_dir.md5($name).'.php';
		if('w' == $method){
			$value = '<?php die();?>'.serialize($value);
			return file_put_contents($sfile, $value);
		}elseif('c' == $method){
			return @unlink($sfile);
		}else{
			if( !is_readable($sfile) )return FALSE;
			$arg_data = file_get_contents($sfile);
			return unserialize(substr($arg_data, 14));
		}
	}
}